import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:grint/data/user_data.dart';
import 'package:grint/entity/user.dart';
import 'package:grint/utils/local_store.dart';
import '../utils/whisper.dart';

class AuthState {
  final bool isLoggedIn; // 是否已登录
  final User? currentUser; // 当前登录用户

  const AuthState({this.isLoggedIn = false, this.currentUser});

  AuthState copyWith({bool? isLoggedIn, User? currentUser}) {
    return AuthState(
      isLoggedIn: isLoggedIn ?? this.isLoggedIn,
      currentUser: currentUser ?? this.currentUser,
    );
  }
}

// 存储键
class AuthStoreKeys {
  static const String currentUserId = 'current_user_id';
}

// 认证逻辑处理类
class AuthCubit extends Cubit<AuthState> {
  final LocalStore _localStore = LocalStore();
  final UserData _userData = UserData();

  AuthCubit() : super(const AuthState());

  Future<void> checkLoginStatus() async {
    final String userId = _localStore.getTextValue(AuthStoreKeys.currentUserId);

    if (userId.isNotEmpty) {
      final User? user = await _userData.getUserById(userId);

      if (user != null) {
        emit(state.copyWith(isLoggedIn: true, currentUser: user));
        return;
      }
    }
    emit(state.copyWith(isLoggedIn: false, currentUser: null));
  }

  // 登录逻辑
  Future<bool> login(
    String username,
    String password, {
    VoidCallback? onLoginSuccess,
  }) async {
    if (username.isEmpty) {
      Whisper.hiss('Please enter your username');
      return false;
    }

    if (password.isEmpty) {
      Whisper.hiss('Please enter your password');
      return false;
    }

    Whisper.chant(message: 'Logging in...');

    await Future.delayed(const Duration(seconds: 2));

    try {
      final User? user = await _userData.validateUser(username, password);

      if (user != null) {
        await _localStore.setTextValue(AuthStoreKeys.currentUserId, user.id);

        emit(state.copyWith(isLoggedIn: true, currentUser: user));

        Whisper.silence();

        Whisper.murmur('Login successful');

        // 调用登录成功回调
        onLoginSuccess?.call();

        return true;
      } else {
        Whisper.silence();
        Whisper.hiss('Username or password is incorrect');
        return false;
      }
    } catch (error) {
      Whisper.silence();
      Whisper.shriek('Login failed: ${error.toString()}');
      return false;
    }
  }

  // 注册逻辑
  Future<bool> register(
    String username,
    String password,
    String confirmPassword, {
    VoidCallback? onRegisterSuccess,
  }) async {
    if (username.isEmpty) {
      Whisper.hiss('Please enter your username');
      return false;
    }

    if (password.isEmpty) {
      Whisper.hiss('Please enter your password');
      return false;
    }

    if (confirmPassword.isEmpty) {
      Whisper.hiss('Please confirm your password');
      return false;
    }

    if (password != confirmPassword) {
      Whisper.hiss('The passwords you entered do not match');
      return false;
    }

    Whisper.chant(message: 'Registering...');

    try {
      // 2. 检查用户名是否存在
      final users = await _userData.getAllUsers();
      final bool usernameExists = users.any((u) => u.username == username);

      if (usernameExists) {
        Whisper.hiss('Username already exists');
        return false;
      }

      // 3. 创建新用户
      final String userId = 'user_${DateTime.now().millisecondsSinceEpoch}';
      final newUser = User(
        id: userId,
        username: username,
        password: password,
        name: username,
        avatar: 'assets/images/avatar-one.png',
        description: '',
      );

      final bool success = await _userData.addUser(newUser);

      if (success) {
        await _localStore.setTextValue(AuthStoreKeys.currentUserId, userId);

        emit(state.copyWith(isLoggedIn: true, currentUser: newUser));

        Whisper.silence();

        Whisper.murmur('Registration successful');

        // 调用注册成功回调
        onRegisterSuccess?.call();

        return true;
      } else {
        Whisper.silence();
        Whisper.hiss('Registration failed');
        return false;
      }
    } catch (error) {
      Whisper.silence();
      Whisper.shriek('Registration failed: ${error.toString()}');
      return false;
    }
  }

  // Apple登录
  Future<bool> loginWithApple() async {
    Whisper.chant(message: 'Logging in...');

    try {
      await Future.delayed(const Duration(seconds: 1));

      Whisper.silence();

      Whisper.murmur('Apple login successful');

      return true;
    } catch (error) {
      Whisper.silence();
      Whisper.shriek('Apple login failed');
      return false;
    }
  }

  // 更新用户信息
  Future<bool> updateUserProfile({
    String? name,
    String? description,
    String? avatar,
  }) async {
    if (state.currentUser == null) {
      Whisper.hiss('No user logged in');
      return false;
    }

    try {
      // 创建更新后的用户对象
      final updatedUser = User(
        id: state.currentUser!.id,
        username: state.currentUser!.username,
        password: state.currentUser!.password,
        name: name ?? state.currentUser!.name,
        avatar: avatar ?? state.currentUser!.avatar,
        description: description ?? state.currentUser!.description,
      );

      // 更新到数据库
      final success = await _userData.updateUser(updatedUser);

      if (success) {
        // 更新当前状态
        emit(state.copyWith(currentUser: updatedUser));
        // Whisper.murmur('Profile updated successfully');
        return true;
      } else {
        Whisper.hiss('Failed to update profile');
        return false;
      }
    } catch (error) {
      Whisper.hiss('Update failed: ${error.toString()}');
      return false;
    }
  }

  // 登出
  Future<void> logout() async {
    await _localStore.removeValue(AuthStoreKeys.currentUserId);

    emit(state.copyWith(isLoggedIn: false, currentUser: null));

    Whisper.silence();

    Whisper.murmur('Logged out successfully');
  }
}
